package com.gaga.console.core.controller.bv;


import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gaga.common.enums.DelFlag;
import com.gaga.common.enums.ScriptItemFileType;
import com.gaga.common.enums.ScriptType;
import com.gaga.common.path.ApiPath;
import com.gaga.common.result.Result;
import com.gaga.console.base.controller.BaseController;
import com.gaga.console.base.entity.PageParams;
import com.gaga.console.base.mybatisplus.LambdaQueryWrapperExt;
import com.gaga.console.base.utils.MyStringUtil;
import com.gaga.console.core.entity.BvScriptCategory;
import com.gaga.console.core.entity.BvScriptItem;
import com.gaga.console.core.entity.vo.ScriptVO;
import com.gaga.console.core.service.BvScriptCategoryService;
import com.gaga.console.core.service.BvScriptItemService;
import com.gaga.metadata.common.utils.StringUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 用户信息表 前端控制器
 *
 * @author liujia
 * @since 2025-03-27
 */
@RestController
@RequestMapping(ApiPath.ROOT + "/bv/script/item")
@Slf4j
public class BvScriptItemController extends BaseController {
    @Autowired
    private BvScriptItemService bvScriptItemService;
    @Autowired
    private BvScriptCategoryService bvScriptCategoryService;

    /**
     * 获取列表
     */
    @ApiOperation(value = "查询list")
    @PostMapping("/list")
    public Result list(@RequestBody PageParams<BvScriptItem> data) {

        LambdaQueryWrapperExt<BvScriptItem> wraps = new LambdaQueryWrapperExt<>();
        wraps.eq(BvScriptItem::getDelFlag, DelFlag.OK.getCode());
        data.buildSpecWrap(wraps);

        IPage<BvScriptItem> page = bvScriptItemService.page(data.buildPage(), wraps);
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            List<BvScriptItem> records = page.getRecords();
            MyStringUtil.sortByName(records);

            records.forEach(item -> {
                if (item.getScriptType().equals(ScriptType.MAIN_VIDEO.getCode()) && StringUtils.isNotBlank(item.getMainVideoLinkItemId())) {
                    List<Long> split = JSON.parseArray(item.getMainVideoLinkItemId(), Long.class);
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < split.size(); i++) {
                        BvScriptItem mainVideoLinkItem = bvScriptItemService.getById(split.get(i));
                        if (mainVideoLinkItem != null) {
                            stringBuilder.append(mainVideoLinkItem.getItemName());
                            if (i != split.size() - 1) {
                                stringBuilder.append(",");
                            }
                        }
                    }

                    item.getMap().put("mainVideoLinkItemName", stringBuilder.toString());
                }
            });
        }
        return Result.ok(data.buildTableResult(page));
    }

    /**
     * 获取列表
     */
    @ApiOperation(value = "根据话术分类id查询list")
    @PostMapping("/getAllList/{scriptCategoryId}")
    public Result list(@PathVariable Long scriptCategoryId) {
        LambdaQueryWrapperExt<BvScriptCategory> wrapsCategory = new LambdaQueryWrapperExt<>();
        wrapsCategory.eq(BvScriptCategory::getDelFlag, DelFlag.OK.getCode());
        wrapsCategory.eq(BvScriptCategory::getId, scriptCategoryId);

        List<BvScriptCategory> categoryList = bvScriptCategoryService.list(wrapsCategory);
        if (CollectionUtils.isEmpty(categoryList)) {
            return Result.ok();
        }

        LambdaQueryWrapperExt<BvScriptItem> wraps = new LambdaQueryWrapperExt<>();
        wraps.eq(BvScriptItem::getDelFlag, DelFlag.OK.getCode());
        wraps.eq(BvScriptItem::getScriptCategoryId, scriptCategoryId);
        wraps.orderByAsc(BvScriptItem::getItemName);

        List<BvScriptItem> list = bvScriptItemService.list(wraps);
        if (CollectionUtils.isEmpty(list)) {
            return Result.ok();
        }

        ScriptVO scriptVO = new ScriptVO();
        List<ScriptVO.ScriptItem> mainAudioFileList = new ArrayList<>();
        List<ScriptVO.ScriptItem> mainVideoFileList = new ArrayList<>();

        Map<String, List<BvScriptItem>> scriptTypeMap = list.stream().collect(Collectors.groupingBy(BvScriptItem::getScriptType));
        for (String scriptType : scriptTypeMap.keySet()) {
            List<BvScriptItem> bvScriptItemList = scriptTypeMap.get(scriptType);
            if (CollectionUtils.isEmpty(bvScriptItemList)) {
                continue;
            }
            // todo 保存的时候需要控制，一个分类id只能有一个keyword和userEnter
            if (ScriptType.KEYWORD.getCode().equals(scriptType)) {
                scriptVO.setKeyword(bvScriptItemList.get(0).getScriptContent());
                scriptVO.setKeywordId(bvScriptItemList.get(0).getId());
            } else if (ScriptType.USER_ENTER.getCode().equals(scriptType)) {
                scriptVO.setUserEnter(bvScriptItemList.get(0).getScriptContent());
                scriptVO.setUserEnterId(bvScriptItemList.get(0).getId());
            }
//            else if (ScriptType.MAIN_VIDEO.getCode().equals(scriptType)) {
//                MyStringUtil.sortByName(bvScriptItemList);
//
//                for (BvScriptItem bvScriptItem : bvScriptItemList) {
//                    ScriptVO.ScriptItem scriptItem = new ScriptVO.ScriptItem();
//                    scriptItem.setId(bvScriptItem.getId());
//                    scriptItem.setName(bvScriptItem.getItemName());
//                    scriptItem.setContent(bvScriptItem.getScriptContent());
//                    scriptItem.setItemFileType(bvScriptItem.getItemFileType());
//                    mainVideoFileList.add(scriptItem);
//                }
//            }
            else if (ScriptType.MAIN_AUDIO.getCode().equals(scriptType) || ScriptType.MAIN_VIDEO.getCode().equals(scriptType)) {
                MyStringUtil.sortByName(bvScriptItemList);

                LinkedHashMap<String, List<BvScriptItem>> itemNameMap = bvScriptItemList.stream()
                        .parallel()
                        .collect(Collectors.groupingBy(
                                BvScriptItem::getItemName,
                                LinkedHashMap::new,
                                Collectors.toList()
                        ));
                for (String itemName : itemNameMap.keySet()) {
                    List<BvScriptItem> bvScriptItems = itemNameMap.get(itemName);
                    if (CollectionUtils.isEmpty(bvScriptItems)) {
                        continue;
                    }
                    if (ScriptItemFileType.FOLDER.getCode().equals(bvScriptItems.get(0).getItemFileType())) {
                        List<String> collect = bvScriptItems.stream().map(BvScriptItem::getScriptContent).collect(Collectors.toList());
                        ScriptVO.ScriptItem scriptItem = new ScriptVO.ScriptItem();
                        scriptItem.setId(bvScriptItems.get(0).getId());
                        scriptItem.setName(bvScriptItems.get(0).getItemName());
                        scriptItem.setContent(StringUtils.join(collect, "\n"));
                        scriptItem.setItemFileType(bvScriptItems.get(0).getItemFileType());
                        if (ScriptType.MAIN_AUDIO.getCode().equals(scriptType)) {
                            mainAudioFileList.add(scriptItem);
                        } else {
                            mainVideoFileList.add(scriptItem);
                        }
                    } else {
                        ScriptVO.ScriptItem scriptItem = new ScriptVO.ScriptItem();
                        scriptItem.setId(bvScriptItems.get(0).getId());
                        scriptItem.setName(bvScriptItems.get(0).getItemName());
                        scriptItem.setContent(bvScriptItems.get(0).getScriptContent());
                        scriptItem.setItemFileType(bvScriptItems.get(0).getItemFileType());
                        if (ScriptType.MAIN_AUDIO.getCode().equals(scriptType)) {
                            mainAudioFileList.add(scriptItem);
                        } else {
                            mainVideoFileList.add(scriptItem);
                        }
                    }
                }
            }
        }

        scriptVO.setMainAudioFileList(mainAudioFileList);
        scriptVO.setMainVideoFileList(mainVideoFileList);

        return Result.ok(scriptVO);
    }

    /**
     * 根据详细信息
     */
    @ApiOperation(value = "获取单个记录")
    @GetMapping(value = "/{id}")
    public Result getEntity(@PathVariable Long id) {
        return Result.ok(bvScriptItemService.getById(id));
    }

    /**
     * 保存
     */
    @ApiOperation(value = "保存记录")
    @PostMapping("/save")
    public Result save(@Validated @RequestBody BvScriptItem entity) {
        BvScriptItem scriptItem = bvScriptItemService.getById(entity.getId());
        if (scriptItem == null) {
            return Result.fail("该记录不存在");
        }
        BvScriptCategory category = bvScriptCategoryService.getById(scriptItem.getScriptCategoryId());
        if (category == null) {
            return Result.fail("分类记录不存在");
        }
        bvScriptItemService.saveOrUpdate(entity);
        String txtPath = category.getPath() + File.separator + scriptItem.getFilePath();

        try (FileWriter writer = new FileWriter(txtPath)) { // try-with-resources 自动关闭流
            writer.write(entity.getScriptContent());
        } catch (IOException e) {
            log.error("写入文件时出错: " + e.getMessage());
        }

        return Result.ok();
    }


    /**
     * 删除
     */
    @ApiOperation(value = "删除记录")
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable Long[] ids) {

        if (ArrayUtil.isEmpty(ids)) {
            return toAjaxBoolean(false);
        }
        List<BvScriptItem> removeEntityList = Arrays.stream(ids)
                .map(id -> {
                    BvScriptItem entity = new BvScriptItem().setId(id);
                    entity.setDelFlag(DelFlag.DELETED.getCode());
                    entity.setDeleteTime(new Date());
                    return entity;
                }).collect(Collectors.toList());

        return toAjaxBoolean(bvScriptItemService.updateBatchById(removeEntityList));
    }

}
